package com.course.web.view;

import com.course.domain.dao.ExamDao;
import com.course.domain.model.Exam;
import com.course.web.component.base.BaseEdit;
import com.course.web.page.AdminUI;
import com.vaadin.data.Binder;
import com.vaadin.navigator.View;
import com.vaadin.navigator.ViewChangeListener;
import com.vaadin.server.ExternalResource;
import com.vaadin.spring.annotation.SpringView;
import com.vaadin.ui.*;

@SpringView(name = ExamInfoView.NAME, ui = AdminUI.class)
public class ExamInfoView extends CustomComponent implements View {
    public static final String NAME = "exam-info";

    private final ExamDao examDao;
    private final ExamEdit examEdit;

    private Exam exam;
    private Link link;

    public ExamInfoView(ExamDao examDao) {
        this.examDao = examDao;
        this.examEdit = new ExamEdit();
        init();
    }

    @Override
    public void enter(ViewChangeListener.ViewChangeEvent event) {
        exam = examDao.findOne(1);
        if (exam != null) {
            link.setResource(new ExternalResource(exam.getReportLink()));
        }
    }

    private void init() {
        VerticalLayout root = new VerticalLayout();
        link = new Link("测验模板", null);
        Button button = new Button("修改模板");
        root.addComponent(link);
        root.addComponent(button);
        button.addClickListener(event -> examEdit.show(getUI(), exam));
        setCompositionRoot(root);
    }


    private class ExamEdit extends BaseEdit<Exam> {
        ExamEdit() {
            super(Exam.class);

            FormLayout form = new FormLayout();
            TextField report = new TextField("评价模板链接");
            form.addComponent(report);
            initEdit(form);

            Binder<Exam> binder = binder();
            binder.forField(report).bind("reportLink");

            setHandler(this::save);
        }

        private void save(Exam exam) {
            examDao.save(exam);
            link.setResource(new ExternalResource(exam.getReportLink()));
        }
    }

}
